package com.cai.config;

import com.cai.enumerator.OrderStatusChangeEventEnum;
import com.cai.enumerator.OrderStatusEnum;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/**
 * @Author czq
 * @Package com.cai.config
 * @Date 2024/5/20 12:41
 * @description: 订单状态机
 */
@Configuration
@EnableStateMachine//开启状态机
public class OrderStatusMachineConfig extends StateMachineConfigurerAdapter<OrderStatusEnum, OrderStatusChangeEventEnum> {
    /**
     * 配置状态
     */
    @Override
    public void configure(StateMachineStateConfigurer<OrderStatusEnum, OrderStatusChangeEventEnum> states) throws Exception {
        states.withStates()
                .initial(OrderStatusEnum.WAIT_PAYMENT)//初始状态 待支付
                .end(OrderStatusEnum.FINISH)//结束状态完成
                .states(EnumSet.allOf(OrderStatusEnum.class));
    }

    /**
     * 配置状态转换时间关系
     *
     * @param transitions
     * @throws Exception
     */
    @Override
    public void configure(StateMachineTransitionConfigurer<OrderStatusEnum, OrderStatusChangeEventEnum> transitions) throws Exception {
        transitions
                // 待支付 到 待发货 状态 状态事件：支付
                .withExternal().source(OrderStatusEnum.WAIT_PAYMENT).target(OrderStatusEnum.WAIT_DELIVER)
                .event(OrderStatusChangeEventEnum.PAYED)
                .and()
                // 待发货 到 待收货 状态 状态事件：发货
                .withExternal().source(OrderStatusEnum.WAIT_DELIVER).target(OrderStatusEnum.WAIT_RECEIVED)
                .event(OrderStatusChangeEventEnum.DELIVERY)
                .and()
                // 待收货 导 完成 状态 状态事件：收货
                .withExternal().source(OrderStatusEnum.WAIT_RECEIVED).target(OrderStatusEnum.FINISH)
                .event(OrderStatusChangeEventEnum.RECEIVED);

    }
}
